export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{M}-{d} {h}:{m}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (typeof time === 'string') {
      if (/^[0-9]+$/.test(time)) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    M: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    m: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/{([yMdhmsa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return timeStr
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

export function resetTime(value) {
  var time = new Date(value)
  // 获取当前时间
  var nowTime = new Date()
  // 获取时间差
  var timediff = time.getTime() - nowTime.getTime()
  // 获取还剩多少天
  var day = parseInt(timediff / 1000 / 60 / 60 / 24)
  console.log(parseInt(timediff / 1000 / 60 / 60), timediff / 1000 / 60 / 60 / 24, day, '789789')
  // 获取还剩多少小时
  var hour = parseInt(timediff / 1000 / 60 / 60)
  // //获取还剩多少分钟
  var minute = parseInt(timediff / 1000 / 60)
  // //获取还剩多少秒
  var second = parseInt(timediff / 1000)
  if (day > 0) {
    return '倒计时：' + day + '天'
  } else if (hour > 0) {
    return '倒计时：' + hour + '小时'
  } else if (minute > 0) {
    return '倒计时：' + minute + '分钟'
  } else if (second > 0) {
    return '活动即将开始'
  } else {
    return '活动进行中'
  }
}
